package com.mnnu.system.service.impl;

import com.mnnu.common.domain.TreeSelect;
import com.mnnu.common.domain.entity.SysDept;
import com.mnnu.system.mapper.SysDeptMapper;
import com.mnnu.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ISysDeptServiceImpl implements ISysDeptService {

    @Autowired
    public SysDeptMapper sysDeptMapper;

    /**
     * 条件查询部门信息
     * @param dept
     * @return
     */
    public List<SysDept> selectDept(SysDept dept) {
        return sysDeptMapper.selectDept(dept);
    }

    /**
     * 查询部门下拉树
     * @param dept
     * @return
     */
    public List<TreeSelect> getDeptTreeSelect(SysDept dept) {
        // 查询部门信息
        List<SysDept> depts = selectDept(dept);
        // 划分树形结构
        List<SysDept> deptsTree = buildDeptTree(depts);
        // 流转换返回
        return deptsTree.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构造下拉树结构
     * @param depts
     * @return
     */
    private List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> deptsTree = new ArrayList<>();
        // 获取所有部门id
        List<Long> ids = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        // 找到根节点
        for (SysDept dept : depts) {
            if (!ids.contains(dept.getParentId())) {
                // 递归
                recursionFn(dept, depts);
                deptsTree.add(dept);
            }
        }
        return deptsTree;
    }

    /**
     * 递归构造
     * @param dept
     * @param depts
     */
    private void recursionFn(SysDept dept, List<SysDept> depts) {
        // 找到当前根节点的所有子节点
        List<SysDept> childrenDepts = getChildren(dept, depts);
        // 判断当前节点有无子节点，递归结束条件
        if (hasChild(childrenDepts))
            return;

        dept.setChildren(childrenDepts);
        // 寻找以当前子节点为根节点的子节点
        for (SysDept childrenDept : childrenDepts) {
            recursionFn(childrenDept, depts);
        }

    }

    /**
     * 有无孩子节点
     * @param childrenDepts
     * @return
     */
    private static boolean hasChild(List<SysDept> childrenDepts) {
        if (childrenDepts.size() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取子节点
     * @param dept
     * @param depts
     * @return
     */
    private static List<SysDept> getChildren(SysDept dept, List<SysDept> depts) {
        List<SysDept> childrenDepts = new ArrayList<>();
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept next = it.next();
            if (dept.getDeptId() == next.getParentId()) {
                // 是当前节点的子节点，加入集合
                childrenDepts.add(next);
            }
        }
        return childrenDepts;
    }
}
